<template>
  <div>
    <el-card>
      <el-form inline :disabled="isAdd">
        <el-form-item label="一级分类">
          <el-select placeholder="请选择" v-model="list.id1">
            <!-- 这里label显示的文本,value绑定的是id  -->
            <el-option
              v-for="item1 in list.category1List"
              :key="item1.id"
              :label="item1.name"
              :value="item1.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类">
          <el-select v-model="list.id2" placeholder="请选择">
            <el-option
              v-for="item2 in list.category2List"
              :key="item2.id"
              :label="item2.name"
              :value="item2.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="三级分类">
          <el-select v-model="list.id3" placeholder="请选择">
            <el-option
              v-for="item3 in list.category3List"
              :key="item3.id"
              :label="item3.name"
              :value="item3.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>
    <AttrList
      :ids="{ id1: list.id1, id2: list.id2, id3: list.id3 }"
      @toggle="changeIsAdd"
      v-if="!isAdd"
    />
    <AddAttr v-else @toggle="changeIsAdd" :id3="list.id3" />
  </div>
</template>
<script lang="ts">
export default {
  name: "XAttr",
};
</script>
<script lang="ts" setup>
import { reactive, onMounted, watch, ref } from "vue";
import type {
  ArrayCategory1,
  ArrayCategory2,
  ArrayCategory3,
} from "@/api/product/model/index";
import { reqCategory1, reqCategory2, reqCategory3 } from "@/api/product/attr";
import AttrList from "@/components/attrList/index.vue";
import AddAttr from "@/components/addAttr/index.vue";
/***
 * 分类页面
 */
const isAdd = ref(false);
function changeIsAdd(bool: boolean) {
  isAdd.value = bool;
}
interface categoryAllType {
  id1: number | undefined;
  id2: number | undefined;
  id3: number | undefined;
  category1List: ArrayCategory1;
  category2List: ArrayCategory2;
  category3List: ArrayCategory3;
}
const list = reactive<categoryAllType>({
  id1: undefined,
  id2: undefined,
  id3: undefined,
  category1List: [],
  category2List: [],
  category3List: [],
});
onMounted(request);
async function request() {
  const result = await reqCategory1();
  list.category1List = result;
}
watch(
  () => list.id1,
  async (newValue) => {
    if (!newValue) return;
    const result = await reqCategory2(newValue);
    list.category2List = result;
    list.id2 = undefined;
    list.id3 = undefined;
  }
);
watch(
  () => list.id2,
  async (newValue) => {
    if (!newValue) return;
    const result = await reqCategory3(newValue);
    list.category3List = result;
    list.id3 = undefined;
  }
);
</script>
<style scoped></style>
